package com.qls.web.modules.op.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qls.core.constant.Constant;
import com.qls.core.dto.PushHotelBody;
import com.qls.core.dto.PushRpBody;
import com.qls.core.entity.*;
import com.qls.core.utils.R;
import com.qls.rabbitmq.SendMsg;
import com.qls.web.common.utils.PageUtils;
import com.qls.web.modules.dt.service.DtService;
import com.qls.web.modules.dt.service.StorePfService;
import com.qls.web.modules.dt.service.StoreService;
import com.qls.web.modules.ht.service.HtLogicRoomService;
import com.qls.web.modules.op.service.GroupService;
import com.qls.web.modules.op.service.HtlGroupService;
import com.qls.web.modules.op.service.PushGroupHotelService;
import com.qls.web.modules.op.service.TaskStatusService;
import com.qls.web.modules.sys.controller.AbstractController;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 分组
 *
 * @author yj
 * @email yj@gmail.com
 * @date 2021-08-31 10:42:11
 */
@RestController
@RequestMapping("op/group")
public class GroupController extends AbstractController {
    @Autowired
    private GroupService groupService;

    @Autowired
    private HtlGroupService htlGroupService;

    @Autowired
    private PushGroupHotelService pushGroupHotelService;

    @Autowired
    private DtService dtService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private StorePfService storePfService;

    @Autowired
    private TaskStatusService taskStatusService;

    @Autowired
    private SendMsg sendMsg;

    @Autowired
    private HtLogicRoomService htLogicRoomService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("op:group:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = groupService.sqlQueryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("op:group:list")
    public R info(@PathVariable("id") Integer id) {
        OpGroup group = groupService.getById(id);
        return R.ok().put("group", group);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("op:group:save")
    public R save(@RequestBody OpGroup group) {
        groupService.save(group);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("op:group:update")
    public R update(@RequestBody OpGroup group) {
        OpGroup group1 = new OpGroup();
        group1.setId(group.getId());
        group1.setGroupName(group.getGroupName());
        groupService.updateById(group1);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete/{id}")
    @RequiresPermissions("op:group:delete")
    public R delete(@PathVariable("id") Integer id) {
        System.out.println(id);
        Long count = htlGroupService.sqlQueryByGroupId(id);
        if (count > 0) {
            return R.error("请先删除分组下的酒店");
        }
        groupService.removeById(id);
        return R.ok("删除成功");
    }

    /**
     * 分组下酒店推送
     *
     * @param groupId Long
     * @return R
     */
    @RequestMapping("/push")
    @RequiresPermissions("op:group:push")
    public R push(@RequestParam("groupId") Integer groupId) {
        pushGroupHotelService.pushGroup(groupId);
        return R.ok("开始推送");
    }

    /**
     * 查询
     *
     * @param params
     * @return
     */
    @RequestMapping("/dtpf")
    @RequiresPermissions("op:group:list")
    public R listDtPf(@RequestParam Map<String, Object> params) {
        String inSql = "SELECT id FROM dt_dt WHERE FIND_IN_SET(id, getChild(" + getUserDtId() + "))";
        List<DtDt> dts = dtService.getBaseMapper().selectList(new QueryWrapper<DtDt>().inSql("id", inSql));
        List<DtStorePf> spfs = storePfService.getBaseMapper().selectList(new QueryWrapper<DtStorePf>());
        return R.ok().put("dts", dts).put("spfs", spfs);
    }

    /**
     * 查询机构下的店铺下拉列表
     */
    @RequestMapping("/store")
    @RequiresPermissions("op:group:list")
    public R select(@RequestParam Map<String, Object> params) {
        List<DtStore> list = storeService.queryByDtId(params);
        return R.ok().put("list", list);
    }

    @RequestMapping("/group")
    @RequiresPermissions("op:group:list")
    public R listGroup(@RequestParam Map<String, Object> params) {
        String ownerDeptStr = getUserOwnerDept();
        String[] ownerDept = null;
        String dtId = (String) params.get("dtId");
        // 如果选择了机构，查询指定机构的数据
        if (!StringUtils.isEmpty(dtId) && !StringUtils.equals(dtId, getUserDtId().toString())) {
            ownerDept = new String[1];
            ownerDept[0] = dtId;
        } else {
            ownerDept = ownerDeptStr.split("\\,");
        }
        params.put("ownerDept", ownerDept);
        List<OpGroup> list = groupService.sqlQuery(params);
        return R.ok().put("list", list);
    }

    /**
     * 删除分组下和店铺上的酒店和rp
     *
     * @param params Map<String, Object>
     * @return R
     */
    @RequestMapping("/delhtl")
    @RequiresPermissions("op:group:htldel")
    public R delGroupHtl(@RequestParam Map<String, Object> params) {
        Integer groupId = Integer.valueOf(params.get("groupId").toString());
        OpGroup opGroup = groupService.queryStoreIdById(groupId);
        List<Long> hotelCodes = htlGroupService.getHotelIdByGroupId(groupId);
        // 结束标志
        hotelCodes.add(-1L);
        // 生成任务
        OpTaskStatus opTaskStatus = new OpTaskStatus();
        Integer taskCode = Integer.valueOf(System.currentTimeMillis() / 1000 + "");
        opTaskStatus.setTaskCode(taskCode);
        opTaskStatus.setTaskName(String.format("分组[%s]酒店全量删除", opGroup.getGroupName()));
        opTaskStatus.setStartTime(new Date());
        opTaskStatus.setTotal(hotelCodes.size() - 1);
        opTaskStatus.setDtId(opGroup.getDtId());
        taskStatusService.save(opTaskStatus);
        // 扔进队列
        PushHotelBody pushHotelBody = new PushHotelBody();
        for (Long hotelCode : hotelCodes) {
            pushHotelBody.setType(-1);
            pushHotelBody.setHotelId(hotelCode);
            pushHotelBody.setTaskId(taskCode);
            pushHotelBody.setStoreId(opGroup.getStoreId());
            sendMsg.execute(Constant.RabbitMq.HOTEL, opGroup.getStoreId(), pushHotelBody);
        }
        return R.ok();
    }

    /**
     * 删除分组铺上的所有自定义价格政策的rp
     *
     * @param params Map<String, Object>
     * @return R
     */
    @RequestMapping("/delrp")
    @RequiresPermissions("op:group:delete")
    public R delGroupRp(@RequestParam Map<String, Object> params) {
        Integer groupId = Integer.valueOf(params.get("groupId").toString());
        OpGroup opGroup = groupService.queryStoreIdById(groupId);
        List<Long> rpCodes = htLogicRoomService.queryRpCodesByGroup(groupId);
        // 结束标志
        rpCodes.add(-1L);
        // 生成任务
        OpTaskStatus opTaskStatus = new OpTaskStatus();
        Integer taskCode = Integer.valueOf(System.currentTimeMillis() / 1000 + "");
        opTaskStatus.setTaskCode(taskCode);
        opTaskStatus.setTaskName(String.format("分组[%s]rp全量删除", opGroup.getGroupName()));
        opTaskStatus.setStartTime(new Date());
        opTaskStatus.setTotal(rpCodes.size() - 1);
        opTaskStatus.setDtId(opGroup.getDtId());
        taskStatusService.save(opTaskStatus);
        PushRpBody pushRpBody = new PushRpBody();
        for (Long rpCode : rpCodes) {
            pushRpBody.setCrpIds(null);
            pushRpBody.setRpCode(rpCode);
            pushRpBody.setStoreId(opGroup.getStoreId());
            pushRpBody.setTaskId(taskCode);
            pushRpBody.setType(-1);
            sendMsg.execute(Constant.RabbitMq.RP, opGroup.getStoreId(), pushRpBody);
        }
        return R.ok();
    }

    /**
     * 开启订单直连
     *
     * @return
     */
    @RequestMapping("direct/start")
    public R directStart(@RequestParam Map<String, Object> params) {
        Integer groupId = Integer.valueOf(params.get("groupId").toString());
        OpGroup opGroup = new OpGroup();
        opGroup.setId(groupId);
        opGroup.setIsDirect(1);
        groupService.updateById(opGroup);
        return R.ok();
    }

    /**
     * 关闭订单直连
     *
     * @return
     */
    @RequestMapping("direct/stop")
    public R directStop(@RequestParam Map<String, Object> params) {
        Integer groupId = Integer.valueOf(params.get("groupId").toString());
        OpGroup opGroup = new OpGroup();
        opGroup.setId(groupId);
        opGroup.setIsDirect(0);
        groupService.updateById(opGroup);
        return R.ok();
    }

}
